<template>
    <div>
        <el-form :model="form" label-width="40px">

            <el-form-item label="名称" prop="loopName">
                <el-input v-model="form.loopName" readonly/>
            </el-form-item>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="站号" prop="siteNumber">
                        <el-input v-model="form.siteNumber" readonly/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="位置" prop="position">
                        <el-input v-model="form.position" readonly/>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="数值" prop="loopValue">
                        <el-input v-model="form.loopValue" readonly/>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="状态">
                        <!--                        <el-tag :type="form.status === '1' ? 'success' : 'danger'" disable-transitions>-->
                        <!--                            {{ form.status === '1' ? '正常' : '异常' }}-->
                        <!--                        </el-tag>-->
                        <span v-if="form.status==='1'">正常</span>
                        <span v-else>异常</span>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="模式">
                        <span v-if="form.loopWorkType==='1'">普通</span>
                        <span v-else>脉冲</span>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-form-item label="操作">
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="success" size="small" :loading="openLoop.loading" @click="openLoopF">
                            {{ openLoop.text }}
                        </el-button>
                    </el-col>

                    <el-col :span="1.5">
                        <el-button type="success" size="small" :loading="closeLoop.loading" @click="closeLoopF">
                            {{ closeLoop.text }}
                        </el-button>
                    </el-col>

                    <el-col :span="1.5">
                        <el-button type="success" size="small" :loading="readLoop.loading" @click="readLoopF">
                            {{ readLoop.text }}
                        </el-button>
                    </el-col>

                </el-row>
            </el-form-item>

            <el-form-item label="模式">
                <el-row :gutter="10" class="mb8">

                    <el-col :span="1.5">
                        <el-button type="success" size="small" :loading="normal.loading" @click="normalF">
                            {{ normal.text }}
                        </el-button>
                    </el-col>

                    <el-col :span="1.5">
                        <el-button type="success" size="small" :loading="pulse.loading" @click="pulseF">
                            {{ pulse.text }}
                        </el-button>
                    </el-col>

                </el-row>
            </el-form-item>

        </el-form>
    </div>
</template>

<script>

import { sendMessage } from '@/api/netty/nettyMessage'

export default {
    name: 'index',
    props: {
        loop: {
            type: Object
        }
    },
    data() {
        return {
            openLoop: {
                loading: false,
                text: '开启',
                timer: null,
                waitTime: 20
            },
            closeLoop: {
                loading: false,
                text: '关闭',
                timer: null,
                waitTime: 20
            },
            readLoop: {
                loading: false,
                text: '读取',
                timer: null,
                waitTime: 20
            },
            normal: {
                loading: false,
                text: '普通',
                timer: null,
                waitTime: 20
            },
            pulse: {
                loading: false,
                text: '脉冲',
                timer: null,
                waitTime: 20
            },
            webClientId: this.genUUID(10, 16),
            messageObj: {
                instruction: '0'
            },
            form: {}
        }
    },
    created() {
        this.form = this.loop
    },
    destroyed() {
        if (this.ws !== undefined) {
            this.ws.close()
        }
        this.resetAll()
    },
    methods: {
        normalF() {
            let data = {
                'key': 'normal'
            }
            this.wait(this.normal, '普通')

            this.messageObj.gatewayNumber = this.form.gatewayNumber
            this.messageObj.loopId = this.form.loopId
            this.messageObj.paramType = '1'
            this.messageObj.register = 259
            this.messageObj.operationType = '1'
            this.messageObj.writeValue = '1'
            this.messageObj.data = data
            this.messageObj.webClientId = this.webClientId

            this.send2Web()
        },

        pulseF() {
            let data = {
                'key': 'pulse'
            }
            this.wait(this.pulse, '脉冲')

            this.messageObj.gatewayNumber = this.form.gatewayNumber
            this.messageObj.loopId = this.form.loopId
            this.messageObj.paramType = '1'
            this.messageObj.register = 259
            this.messageObj.operationType = '1'
            this.messageObj.writeValue = '0'
            this.messageObj.data = data
            this.messageObj.webClientId = this.webClientId

            this.send2Web()
        },
        /**
         * 读取
         */
        readLoopF() {
            let data = {
                'key': 'readLoop'
            }
            this.wait(this.readLoop, '读取')

            this.messageObj.gatewayNumber = this.form.gatewayNumber
            this.messageObj.loopId = this.form.loopId
            this.messageObj.paramType = '0'
            this.messageObj.operationType = '0'
            this.messageObj.data = data
            this.messageObj.webClientId = this.webClientId

            this.send2Web()
        },
        /**
         * 关闭
         */
        closeLoopF() {
            let data = {
                'key': 'closeLoop'
            }
            this.wait(this.closeLoop, '关闭')

            this.messageObj.gatewayNumber = this.form.gatewayNumber
            this.messageObj.loopId = this.form.loopId
            this.messageObj.paramType = '0'
            this.messageObj.operationType = '1'
            this.messageObj.writeValue = '0'
            this.messageObj.data = data
            this.messageObj.webClientId = this.webClientId

            this.send2Web()
        },
        /**
         * 开启
         */
        openLoopF() {
            let data = {
                'key': 'openLoop'
            }
            this.wait(this.openLoop, '开启')

            this.messageObj.gatewayNumber = this.form.gatewayNumber
            this.messageObj.loopId = this.form.loopId
            this.messageObj.paramType = '0'
            this.messageObj.operationType = '1'
            this.messageObj.writeValue = '1'
            this.messageObj.data = data
            this.messageObj.webClientId = this.webClientId

            this.send2Web()
        },
        wait(obj, text) {
            obj.loading = true
            obj.text = obj.waitTime + 's'

            // 等待时长
            let time = obj.waitTime - 1
            obj.timer = setInterval(() => {
                if (time === 0) {
                    this.reset(obj, text)
                    this.$message.info('超时')
                } else {
                    obj.text = time + 's'
                    --time
                }
            }, 1000)
        },
        reset(obj, text) {
            clearInterval(obj.timer)
            obj.loading = false
            obj.text = text
        },
        resetAll() {
            this.reset(this.openLoop, '开启')
            this.reset(this.closeLoop, '关闭')
            this.reset(this.readLoop, '读取')
            this.reset(this.normal, '普通')
            this.reset(this.pulse, '脉冲')
        },
        send2Web() {
            sendMessage(this.messageObj).then(response => {
                if (response.code === 200) {
                    // 成功后建立websocket
                    let obj = {
                        'webClientId': this.webClientId,
                        'type': 'login'
                    }
                    this.sendMessage(obj)
                }
            }, error => {
                this.resetAll()
            })
        },
        emitFunc() {
            this.$emit('refresh', {})
        },
        // websocket 发送消息给服务器
        sendMessage(obj) {
            // this.$websocket.sendMsg(JSON.stringify(obj))
            // this.$websocket.sendMsg(obj)
            if (this.ws !== undefined && this.ws.readyState === 1) {
                console.log('已存在')
                // this.$websocket.sendMsg(obj)
            } else {
                this.localSocket(obj)
            }
        },
        localSocket(obj) {
            let that = this
            if ('WebSocket' in window) {
                console.log('您的浏览器支持 WebSocket')
                // console.log('that.ws', that.ws)
                if (that.ws !== undefined && that.ws.readyState === 1) {
                    console.log('存在连接')
                    return
                }

                that.ws = new WebSocket(that.$websocket.url)
                that.$websocket.setWs(that.ws)
                that.ws.onopen = function() {
                    console.log('开始连接')
                    // that.sendMessage(obj)
                    that.$websocket.sendMsg(obj)
                }
                // websocket 接收服务器消息
                that.ws.onmessage = function(result) {
                    console.log('收到websocket回复', result)
                    // console.log('回复data', result.data)
                    that.processData(result.data)
                }
                that.ws.onclose = function() {
                    // 防链接超时，（websocket在一定时间内没有数据交互，就会断开），关闭后重启
                    console.log('连接已关闭')
                    that.ws.close()
                    // setTimeout(() => {
                    //     that.localSocket()
                    // }, 2000)
                }
            } else {
                // 浏览器不支持 WebSocket
                console.log('您的浏览器不支持 WebSocket!')
            }
        },
        processData(json) {
            console.log('json', json)
            let data = {}
            try {
                data = JSON.parse(json)
            } catch (e) {
            }
            // console.log('data', data)
            let webClientId = data['webClientId']
            let cause = data['cause']
            if (webClientId === undefined) {
                return
            }
            // console.log('回复的webClientId', webClientId)
            let text = null
            let key = data['key']
            if ('openLoop' === key) {
                text = '开启成功'
                this.reset(this.openLoop, '开启')
            }
            if ('closeLoop' === key) {
                text = '关闭成功'
                this.reset(this.closeLoop, '关闭')
            }
            if ('readLoop' === key) {
                text = '读取成功'
                this.reset(this.readLoop, '读取')
            }
            if ('normal' === key) {
                text = '已切换为普通模式'
                this.reset(this.normal, '普通')
            }
            if ('pulse' === key) {
                text = '已切换为脉冲模式'
                this.reset(this.pulse, '脉冲')
            }
            // let id = data['id']
            let value = data['value']
            let status = data['status']
            let paramType = data['paramType']
            if (webClientId === this.webClientId) {
                // console.log('id', id)
                if (cause !== undefined) {
                    this.$message.error(cause)
                    this.resetAll()
                    return
                }
                if (value !== undefined) {
                    if (paramType === '0') {
                        this.form.loopValue = value
                    }
                    if (paramType === '1') {
                        this.form.loopWorkType = value
                    }
                }
                if (status !== undefined) {
                    this.form.status = status
                }
                this.$message.success(text)
                this.emitFunc()
            }
        }
    }
}
</script>

<style scoped>

</style>
